package com.lincoln.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class ImageUtil {

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    //链接url下载图片,并生成Base64
    public static byte[] downloadPic(String picUrl) {
        URL url = null;
        try {
            url = new URL(picUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            byte[] bytes = toByteArray(dataInputStream);
            byte[] b = new byte[]{bytes[0], bytes[1], bytes[2], bytes[3]};
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("FFD8FF")) {
                type = "jpg";
            } else if (type.contains("89504E47")) {
                type = "png";
            } else if (type.contains("47494638")) {
                type = "gif";
            } else if (type.contains("424D")) {
                type = "bmp";
            } else {
                type = "none";
            }
            while (bytes.length > 1 * 1024 * 1024) {
                BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes));
                int width = bufferedImage.getWidth(null);
                int height = bufferedImage.getHeight(null);
                width = (int) (width * 0.75);
                height = (int) (height * 0.75);
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
                tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null); // 绘制缩小后的图
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(tag, type, out);
                bytes = out.toByteArray();
            }
            return bytes;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * byte数组转换成16进制字符串
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
